<template>
  <div class="form">
    <div class="header">
      <van-image round width="60" height="60" :src="avatarImg" />
      <p>趣易购</p>
    </div>
    <van-form @submit="onSubmit">
      <van-field v-model="login.username" :border="true" left-icon="manager" name="用户名" placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]" />
      <van-field v-model="login.password" left-icon="lock" type="password" name="密码" placeholder="密请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]" />
      <p class="reg-for-style">
        <a href="" @click.prevent="goRegister">免费注册</a>
        <a href="" @click.prevent="goForget">忘记密码</a>
      </p>
      <div style="margin: 16px;">
        <van-button color="#DB3D3C" block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import avatarImg from '@/assets/avatar_default.png'
import { mapActions } from 'vuex'

export default {
  name: 'Form',
  components: {

  },
  data () {
    return {
      avatarImg: avatarImg,
      login: {
        username: '',
        password: ''
      },
      time: 40
      // isLoading: true
    }
  },
  watch: {

  },
  mounted () {

  },
  beforeDestroy () {
    clearInterval(this.interval)
  },
  methods: {
    // 拿到Actions中的事件
    ...mapActions('Login', { goLogin: 'goLogin' }),
    // 登录提交数据
    onSubmit () {
      // 调用dispatch去请求登录接口，并将数据存入state中
      this.goLogin({ username: this.login.username, password: this.login.password })
      const _that = this
      this.interval = window.setInterval(() => {
        console.log('@@')
        if (!_that.$store.state.Login.token) {
          _that.$toast.loading({
            message: '加载中...',
            forbidClick: true,
            loadingType: 'spinner'
          })
        } else {
          window.localStorage.setItem('token', _that.$store.state.Login.token)
          window.localStorage.setItem('userInfo', _that.$store.state.Login.userInfo)
          _that.$toast.clear()
          _that.$router.replace({ name: 'Mine' })
        }
      }, this.time)
      // console.log(this.$store.state)
    },
    goRegister () {
      this.$router.push({
        name: 'Register'
      })
    },
    goForget () { }
  }
}

</script>
<style scoped lang='scss'>
.header {
  padding: 30px 0;
  font-size: 16px;
  text-align: center;
}

::v-deep .van-field {
  width: 90%;
  border: 1px solid #ccc;
  height: 40px;
  text-align: center;
  // line-height: 32px;
  margin: 15px 20px;
}

::v-deep .van-field__body input {
  font-size: 16px;
}

.reg-for-style {
  position: relative;
  font-size: 14px;
  padding: 0 20px;

  a:nth-child(1) {
    text-align: left;
  }

  a:nth-child(2) {
    position: absolute;
    right: 20px;
    text-align: right;
  }
}
</style>
